package com.example.myblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.myblog.entity.Message;
import com.example.myblog.exception.BaseException;
import com.example.myblog.mapper.MessageMapper;
import com.example.myblog.result.BaseCodeEnum;
import com.example.myblog.service.MessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.myblog.service.UserService;
import com.example.myblog.utils.UserThreadLocal;
import com.example.myblog.vo.MessageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 消息管理 服务实现类
 * </p>
 *
 * @author 叶兴
 * @since 2022-09-29
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    MessageMapper messageMapper;

    UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setMessageMapper(MessageMapper messageMapper) {
        this.messageMapper = messageMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int sendMessage(MessageVO messageVO) throws BaseException {
        // 1. 获取当前用户
        String username = UserThreadLocal.getUserDtoName();
        // 2. 判断发送对象是否存在
        userService.ifUserExists(messageVO.getMessageReceive());
        // 3. 创建消息实体
        Message message = new Message();
        message.setMessageSend(username);
        message.setMessageTime(LocalDateTime.now());
        BeanUtils.copyProperties(messageVO,message);
        // 4. 新增消息
        int i = messageMapper.insert(message);
        if (i != 1) {
            throw new BaseException(BaseCodeEnum.INSERT_FAILED);
        }
        return 0;
    }

    @Override
    public List<Message> getSendMessages() throws BaseException {
        String username = UserThreadLocal.getUserDtoName();
        QueryWrapper<Message> wrapper = new QueryWrapper<>();
        wrapper.eq("message_send",username);
        List<Message> messages = messageMapper.selectList(wrapper);
        if (messages == null || messages.size() == 0) {
            throw new BaseException(BaseCodeEnum.NO_MESSAGES);
        }
        return messages;
    }

    @Override
    public List<Message> getReceiveMessages() throws BaseException {
        String username = UserThreadLocal.getUserDtoName();
        QueryWrapper<Message> wrapper = new QueryWrapper<>();
        wrapper.eq("message_receive",username);
        List<Message> messages = messageMapper.selectList(wrapper);
        if (messages == null || messages.size() == 0) {
            throw new BaseException(BaseCodeEnum.NO_MESSAGES);
        }
        return messages;
    }
}
